// src/router/index.js
import Vue from 'vue';
import VueRouter from 'vue-router';

Vue.use(VueRouter);

const routes = [
  {
    path: '/',
    name: 'login',
    component: () => import('@/views/LoginPage.vue'),
    meta: { title: '登录', keepAlive: true, icon: "user" }
  },
  {
    path: '/home',
    name: 'home',
    component: () => import('@/views/HomePage.vue'),
    meta: { title: '首页', keepAlive: true, icon: "appstore", requiresAuth: true }
  },
  {
    path: '/about',
    name: 'about',
    component: () => import('@/views/AboutPage.vue'),
    meta: { title: '经历', keepAlive: true, icon: "cluster", requiresAuth: true }
  },
  {
    path: '/text',
    name: 'text',
    component: () => import('@/views/TextPage.vue'),
    meta: { title: '简历查看', keepAlive: true, icon: "cluster", requiresAuth: true },
    children: [
      {
        path: '/text/pingmian',
        name: 'pingmian',
        component: () => import('@/views/Bnotes/PingMian.vue'),
        meta: { title: "平面设计师", keepAlive: true, requiresAuth: true }
      },
      {
        path: '/text/web',
        name: 'web',
        component: () => import('@/views/Bnotes/QiamDuan.vue'),
        meta: { title: '前端开发工程师', keepAlive: true, requiresAuth: true }
      },
      {
        path: '/text/node',
        name: 'node',
        component: () => import('@/views/Bnotes/NodeComplete.vue'),
        meta: { title: 'Node.js全栈工程师', keepAlive: true, requiresAuth: true }
      }
    ]
  },
  {
    path: '/manage',
    name: 'manage',
    component: () => import('@/views/ManagePage.vue'),
    meta: { title: '管理', requiresAuth: true 
  ,role:['管理员','超级管理员']}
  },
  {
    path:'/school',
    name:'school',
    component: () => import('@/views/Bnotes/SchoolPage.vue'),
    meta: { title: '学校简介', requiresAuth: false }
  }
];

const router = new VueRouter({
  mode: 'history',
  base: process.env.BASE_URL,
  routes
});

router.beforeEach((to, from, next) => {
  const isLoggedIn = JSON.parse(localStorage.getItem('isLoggedIn'));
  const userRole = localStorage.getItem('userRole');

  if (to.matched.some(record => record.meta.requiresAuth)) {
    if (!isLoggedIn) {
      next({
        path: '/',
        query: { redirect: to.fullPath }
      });
    } else {
      if (to.matched.some(record => record.meta.roles)) {
        if (to.meta.roles.includes(userRole)) {
          next();
        } else {
          next({
            path: '/home',
            query: { redirect: to.fullPath }
          });
        }
      } else {
        next();
      }
    }
  } else {
    next();
  }
});

export default router;